<?php
/**
 * 进云快速开发框架
 * @apple
 */
define('NOSESSION',true);
require '../../core/core.php';
set_exi(function($message='OK',$type='SUCCESS'){
	//如果存在错误，此处整理错误日志，后期完善
	$result = array(
		'return_code' => 'SUCCESS',
		'return_msg' => 'OK',
	);
	$result=array2xml($result);
	echo $result;
	exit;
});
//读取数据
$input = file_get_contents('php://input');
$isxml = true;
if (!empty($input) && empty($_GET['out_trade_no'])) {
	$obj = isimplexml_load_string($input, 'SimpleXMLElement', LIBXML_NOCDATA);
	$data = json_decode(json_encode($obj), true);
	if (empty($data)) {
		exi('error');
	}
	if ($data['result_code'] != 'SUCCESS' || $data['return_code'] != 'SUCCESS'){
		$message=empty($data['return_msg']) ? $data['err_code_des'] : $data['return_msg'];
		$log=date('20y/m/d H:i:s');
		$log.="\n";
		if($data['return_msg']){
			$log.=$data['return_msg'];
		}else{
			$data=var_export($data,true);
			$log.=$data."\n";
		}
		file_put_contents('resource/error_logs/wechat_pay.log',$log,FILE_APPEND);
		exi($message);
	}
	$get = $data;
} else {
	$isxml = false;
	$get = $_GET;
}
$_SESSION['uniacid']=intval($get['attach']);
$_SESSION['this']='custom';
//验证订单
$order=pdo_get('core_paylog',array('tid'=>$get['out_trade_no']));
if(!$order){
	exi('订单不存在','error');
}
//验证签名
if($order['onemerchid']){
    $onewechat=pdo_getcolumn('jy_merch_user',array('uniacid' =>$_SESSION['uniacid'],'id'=>$order['onemerchid']),'onewechat');
    $setting=json_decode($onewechat,true);
}else{
    $setting=uni_setting('pay');
}
$signkey=$setting['wechat_miyue'];
$sign=$get['sign'];
unset($get['sign']);
ksort($get, SORT_STRING);
$string1 = '';
foreach ($get as $key => $v) {
    if (empty($v)) {
        continue;
    }
    $string1 .= "{$key}={$v}&";
}
$string1 .= "key={$signkey}";
$result = strtoupper(md5($string1));
if($result != $sign){
	exi('签名不匹配！','error');
}

$payfee=$order['fee']-$order['di_fee'];
if($payfee!=($get['total_fee']/100)){
	$log=$order['id'].'~'.$payfee.'~'.$get['total_fee']."\n";
	file_put_contents('wechat_error_log.txt',$log,FILE_APPEND);
	//exi('error order','error');
}
if($order['transaction_id']){
	exi('completed','SUCCESS');
}
$_SESSION['uid']=$order['mid'];
//保存支付结果
//抵扣处理
if($order['di_credit'] && $order['di_fee']>0){
	cfc('pay')->up_dipay($order);
}
pdo_update('core_paylog',array('transaction_id'=>$get['transaction_id'],'paytime'=>time()),array('tid'=>$order['tid']));
$_SESSION['uniacid']=$order['uniacid'];
$_SESSION['uid']=$order['mid'];
if($order['merchid']){
	$_SESSION['onemerchid']=$order['merchid'];
}
$result=array('id'=>$order['oid'],'transaction_id'=>$get['transaction_id'],'status'=>1,'pay_type'=>'wechat','fee'=>$order['fee'],'pay_id'=>$order['tid'],'title'=>$order['title'],'async'=>true,'onemerchid'=>$order['onemerchid']);
$_SESSION['payresult']=$result;
$plugin_name=$order['plugin'];
$plugin_type=pdo_get('core_plugins',array('name'=>$plugin_name),'type');
if($plugin_type==4){
	exi('completed','SUCCESS');
}
access($order['back_url']);
exi('OK','SUCCESS');

?>